<?php


include("../Connections/locale.php");

$mssql_host=$hostname_locale;
$mssql_database=$database_locale;
$mssql_username=$username_locale;
$mssql_password=$password_locale;




		

function _mssqldump($mssql_database)
{
	$sql="select table_name from information_schema.tables where table_name not in (select table_name from  information_schema.views)";
	$result= mysql_query($sql);
	if( $result)
	{
		while( $row= mysql_fetch_row($result))
		{
			
			_mssqldump_table_data($row[0]);
			
		}
	}
	else
	{
		echo "/* no tables in $mssql_database */\n";
	}
	mysql_free_result($result);
}

function _mssqldump_table_data($table)
{
	//echo "/* dumping data for table `$table` */\n";
	$sql="select * from $table";
	$result=mysql_query($sql);
	if( $result)
	{
		$num_rows= mysql_num_rows($result);
		$num_fields= mysql_num_fields($result);
		
		if( $num_rows > 0)
		{
			echo "/* Backup della tabella `$table` */\n";
			
			$field_type=array();
			$i=0;
			while( $i < $num_fields)
			{
				$meta= mysql_fetch_field($result, $i);
				array_push($field_type, $meta->type);
				$i++;
			}
			
			//print_r( $field_type);
			echo "insert into `$table` values\n";
			$index=0;
			while( $row= mysql_fetch_row($result))
			{
				echo "(";
				for( $i=0; $i < $num_fields; $i++)
				{
					if( is_null( $row[$i]))
						echo "null";
					else
					{
						switch( $field_type[$i])
						{
							case 'int':
								echo $row[$i];
								break;
							case 'string':
							case 'blob' :
							default:
								echo "'".$row[$i]."'";
								
						}
					}
					if( $i < $num_fields-1)
						echo ",";
				}
				echo ")";
				
				if( $index < $num_rows-1)
					echo ",";
				else
					echo ";";
				echo "\n";
				
				$index++;
			}
		}
	}
	//mysql_free_result($result);
	echo "\n";
}

function _mssql_test($mssql_host,$mssql_database, $mssql_username, $mssql_password)
{
	global $output_messages;
	$link = mysql_connect($mssql_host, $mssql_username, $mssql_password);
	if (!$link) 
	{
	   die('Could not connect: $mssql_host ' );
	}
	else
	{
		//echo("Connected with mssql server:$mssql_username@$mssql_host successfully");
	
		$db_selected = mysql_select_db($mssql_database, $link);
		if (!$db_selected) 
		{
			die('Can\'t use $mssql_database : $mssql_database');
		}
		
	}
	
}

_mssql_test($mssql_host,$mssql_database, $mssql_username, $mssql_password);

header('Content-type: text/plain');
header('Content-Disposition: attachment; filename="'.$mssql_host."_".$mssql_database."_".date('YmdHis').'.sql"');
echo "/* Gestione Abbonamenti - Backup DataBase */\n";
_mssqldump($mssql_database);

	
?>


